/**
 * Copyright 2012 [name of copyright owner]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
package com.qwiki.text;

import java.util.Collections;
import java.util.List;

/**
 * @author xgu
 * 
 * @since Jun 7, 2012
 */
public class TableNode extends Node
{

  private static String starttable = "{|";
  private static String endtable = "|}";
  private static String[] startPatterns = new String[] { "{{Football player national team statistics",
    "{{electiontable" };
  private String startPattern;

  @Override
  public String getText()
  {
    return "";
  }

  @Override
  public List<Node> getChildren()
  {
    return Collections.EMPTY_LIST;
  }

  private boolean matchStartPatterns(char[] buffer, int index)
  {
    for (String startPattern : startPatterns)
    {
      boolean match = match(buffer, index, startPattern);
      if (match)
      {
        this.startPattern = startPattern;
        return true;
      }
    }
    this.startPattern = null;
    return false;
  }

  @Override
  public boolean parse(char[] buffer, int start)
  {
    this.start = start;
    this.buffer = buffer;
    int offset = start;
    boolean matchStartPatterns = false;
    if (((match(buffer, start, "\n") && (offset = Math.max(match(buffer, start + 1, "{|", '\t'), Math.max(match(buffer, start + 1, "{|", ':'), match(buffer, start + 1, "{|", ' ')))) >= 0))
        || (start >= 0 && (offset = Math.max(match(buffer, start, "{|", ':'), match(buffer, start, "{|", ' '))) >= 0)
        || (matchStartPatterns = matchStartPatterns(buffer, start)))
    {
      int i = matchStartPatterns ? start + startPattern.length() : offset + starttable.length();
      TableNode node = new TableNode();
      TemplateNode tnode = new TemplateNode();
      while (i < buffer.length)
      {
        // parse nested TableNode
        if (node.parse(buffer, i))
        {
          i += node.getLength();
          node.parsed = false;
          continue;
        }
        if (tnode.parse(buffer, i))
        {
          i += tnode.getLength();
          tnode.parsed = false;
          continue;
        }
        // parse end of TableNode
        if (match(buffer, i, "\n") && (offset = match(buffer, i + 1, endtable, ' ')) >= 0)
        {
          end = offset + endtable.length();
          parsed = true;
          return true;
        }
        i++;
      }
      // malformed table. eat it all
      parsed = true;
      end = buffer.length;
      return true;
    }
    return false;
  }
}
